#include "cgzCLua.h"
#include "cgzCTcpC.h"
#include "cgzCThreadPool.h"

bool cgzCLua::run(const cgzITask *iTask, cgzCLoopC *pnode)
{
    switch (pnode->getEType())
    {
    case TCPC_ACPT: // 连接成功
    {
        // auto *pnode = static_cast<cgzCAcptC *>(pnode);
        ocall(iTask->m_tref, "accept", {});
    }
    break;
    case TCPC_RECV: // 接收数据
    {
        auto *recv = static_cast<cgzCRecvC *>(pnode);
        auto &head = *(cgzHeader *)recv->m_data;
        auto *data = (const char *)(recv->m_data + sizeof(cgzHeader));
        ocall(iTask->m_tref, "recv", {
            head.mid, 
            {data, (int)head.len},
            (long)head.cid
        });
    }
    break;
    case TCPC_DISC: // 断开连接
    {
        // auto *disc = static_cast<cgzCDiscC *>(pnode);
        ocall(iTask->m_tref, "disc", {});
    }
    break;
    default:
    {
        cgz_this_error("Error: task {} type:{} not support", iTask->getName(), (int)pnode->getEType());
    }
    }
    return true;
}

static int tcp_link(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    const char *name = lua_tostring(L, 1);
    const char *ip = lua_tostring(L, 2);
    int port = lua_tointeger(L, 3);
    int tref = luaL_ref(L, LUA_REGISTRYINDEX);
    void *node = malloc(sizeof(cgzCTcpC));
    int cid = that->getId();
    auto ctcp = new (node) cgzCTcpC(that->m_pool, name, ip, port, cid);
    ctcp->m_tref = tref;
    ctcp->tcpinit();
    return 0;
}

static int tcp_send(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    const char *name = lua_tostring(L, 1);
    int mid = luaL_checkinteger(L, 2);
    size_t len = 0;
    const char *pck = lua_tolstring(L, 3, &len);
    long cid = luaL_checkinteger(L, 4);
    void *node = malloc(sizeof(cgzCSendC));
    auto psend = new (node) cgzCSendC(mid, pck, len, cid);
    that->regTask(name, psend);
    return 0;
}

int cgzCLua::luaopen_tcpC(lua_State *L)
{
    static const luaL_Reg otherlib[] = {
        {"link", tcp_link},
        {"send", tcp_send},
        {NULL, NULL},
    };
    luaL_newlib(L, otherlib);
    return 1;
}